<template>
  <base-search :title="t('keys.agencySettings')" :isShowSearch="1">
    <template #btn>
      <!-- 编辑 -->
      <el-button type="primary" @click="showDrawer">{{ t('keys.edit') }}</el-button>
    </template>
  </base-search>
  <el-row class="contract_base_title">{{ t('keys.BasicInformation') }}</el-row>
  <base-form
    ref="formRefs"
    :isPreview="true"
    v-model="ruleForm"
    :schema="formListModel"
    :rules="rules"
    :options="{ span: 8, labelPosition: 'left', type: 'form', labelWidth: 120 }"
  >
    <template #enableFlag>
      {{ ruleForm.enableFlag && ruleForm.id !== '' ? t('keys.Enable') : !ruleForm.enableFlag && ruleForm.id !== '' ? t('keys.Disable') : '--' }}
    </template>
    <template #empList>
      {{ ruleForm.replaceName || '--' }}
    </template>
    <template #dataTime>
      {{ ruleForm.dataTime?.length ? formatDate(ruleForm.dataTime[0], 'yyyy-MM-dd') + ' - ' + formatDate(ruleForm.dataTime[1], 'yyyy-MM-dd') : '--' }}
    </template>
  </base-form>
  <!-- 编辑 -->
  <zcb-dialog v-model="dialogVisible" :title="t('keys.Process_agent_settings')" width="800px">
    <template #btns>
      <el-button @click.stop="resetForm">{{ t('keys.cancel') }}</el-button>
      <el-button :loading="btnLoading" type="primary" @click="setSubmitData">{{ t('keys.confirm') }}</el-button>
    </template>
    <div class="reg-form-box label-left">
      <base-form
        ref="formRef"
        v-model="dialogRuleForm"
        :schema="formEditModel"
        :rules="rules"
        :options="{ span: 12, labelPosition: 'left', type: 'form', labelWidth: 120 }"
        @change="_change"
      >
        <template #dataTime>
          <el-date-picker
            style="width:100%"
            v-model="dialogRuleForm.dataTime"
            type="daterange"
            :placeholder="t('keys.please_select_date_tips')"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :range-separator="t('keys.To')"
            :start-placeholder="t('keys.StartDate')"
            :end-placeholder="t('keys.EndDate')"
            @change="
              (val) => {
                dialogRuleForm.dataTime = val
              }
            "
          />
        </template>
      </base-form>
    </div>
  </zcb-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { ERR_OK } from 'config/statusCode'
import { postReplaceHandleApi, getReplaceHandleApi } from 'api/home'
import { ElMessage } from 'element-plus'
// import Drawer from 'components/drawer/index.vue'
import pageSelect from 'components/page-select'
import { getTenantId } from 'utils/headerToken'
import { formatDate } from 'utils/index.js'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文
import { useMock } from './hooks/mock.js'
const { agencySetformList } = useMock()
const formListModel = ref(JSON.parse(JSON.stringify(agencySetformList)))
const formEditModel = ref(JSON.parse(JSON.stringify(agencySetformList)))

const emit = defineEmits(['sonOnClick'])

const btnLoading = ref(false)
const formRef = ref(null)
const dialogVisible = ref(false)
const selecOptionList = ref([])
const ruleForm = ref({
  enableFlag: true,
  replaceId: '',
  dataTime: [],
  startTime: '',
  replaceName: '',
  endTime: '',
  remark: '',
  empId: '',
  tenantId: localStorage.getItem('tenantId'),
  versionNum: '',
  empName: '',
  id: ''
})

const getReplaceHandle = async () => {
  const userinfo = JSON.parse(localStorage.getItem('userinfo'))
  const params = {}
  const { code, data } = await getReplaceHandleApi(params, userinfo.empId)
  if (code === ERR_OK) {
    if (data) {
      ruleForm.value.enableFlag = data.enableFlag
      ruleForm.value.replaceId = data.replaceId
      ruleForm.value.dataTime = [data.startTime, data.endTime]
      ruleForm.value.replaceName = data.replaceName
      ruleForm.value.startTime = data.startTime
      ruleForm.value.endTime = data.endTime
      ruleForm.value.remark = data.remark
      ruleForm.value.empId = data.empId
      ruleForm.value.tenantId = data.tenantId
      ruleForm.value.versionNum = data.versionNum
      ruleForm.value.id = data.id
      ruleForm.value.email = data.email
      ruleForm.value.empList = {
        empId: data.replaceId,
        empName: data.replaceName
      }

      if (!ruleForm.value.enableFlag) {
        formListModel.value.forEach((item) => {
          if (item.field != 'enableFlag') {
            item.displayFlag = true
          }
        })
      } else {
        formListModel.value.forEach((item) => {
          item.displayFlag = false
        })
      }
    }
  }
  // descFalg.value = false
  // hassetMore()
}

// 编码规则接口
const codingRuleObj = reactive({
  clearable: true,
  disabled: false,
  assignment: 'replaceId',
  keyName: 'empName',
  keyValue: 'empId',
  optionkeyName: ['empName', 'email'],
  opsName: '', //  编辑回显list数据option的key的值
  opsValue: '', // 编辑回显list数据option的value的key的值
  Url: `/zemd/v1/${getTenantId()}/emp`,
  params: {}
})

const rules = reactive({
  status: [{ required: true, message: t('keys.Please_Process_agent'), trigger: 'change' }],
  replaceId: [{ required: true, message: t('keys.Please_agent'), trigger: 'change' }],
  dataTime: [{ required: true, message: t('keys.Please_period_of_procuration'), trigger: 'change' }],
  remark: [{ required: true, message: t('keys.Please_reason'), trigger: 'blur' }]
})
const dialogRuleForm = ref({})
const showDrawer = () => {
  dialogRuleForm.value = JSON.parse(JSON.stringify(ruleForm.value))
  if (!dialogRuleForm.value.enableFlag) {
    formEditModel.value.forEach((item) => {
      if (item.field != 'enableFlag') {
        item.displayFlag = true
      }
    })
  } else {
    formEditModel.value.forEach((item) => {
      item.displayFlag = false
    })
  }
  // selecOptionList.value =
  //   ruleForm.value?.replaceId && ruleForm.value?.email
  //     ? [
  //         {
  //           empId: ruleForm.value.replaceId,
  //           id: ruleForm.value.replaceId,
  //           empName: ruleForm.value.replaceName,
  //           email: ruleForm.value.email
  //         }
  //       ]
  //     : []
  formEditModel.value[1].componentProps.selecOptionList =
    ruleForm.value?.replaceId && ruleForm.value?.email
      ? [
          {
            empId: ruleForm.value.replaceId,
            id: ruleForm.value.replaceId,
            empName: ruleForm.value.replaceName,
            email: ruleForm.value.email
          }
        ]
      : []
  dialogVisible.value = true
}
const _change = (val) => {
  if (val.fieldCode == 'empList' && val.value) {
    dialogRuleForm.value.replaceId = val.value?.empId
    dialogRuleForm.value.replaceName = val.value?.empName
    return
  }
  if (val.fieldCode == 'enableFlag' && !val.value) {
    formEditModel.value.forEach((item) => {
      if (item.field != 'enableFlag') {
        item.displayFlag = true
      }
    })
  } else {
    formEditModel.value.forEach((item) => {
      item.displayFlag = false
    })
  }
}

const pageChange = (val, a, b, c, obj) => {
  dialogRuleForm.value.replaceId = val
  dialogRuleForm.value.replaceName = obj.empName
}
// 重置参数
const resetForm = () => {
  dialogVisible.value = false
}
const setSubmitData = () => {
  btnLoading.value = true
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const userinfo = JSON.parse(localStorage.getItem('userinfo'))
      const params = { ...dialogRuleForm.value }
      params.startTime = params.dataTime?.length ? params.dataTime[0] + (params.dataTime[0].indexOf('00:00:00') != -1 ? '' : ' 00:00:00') : ''
      params.endTime = params.dataTime?.length ? params.dataTime[1] + (params.dataTime[1].indexOf('23:59:59') != -1 ? '' : ' 23:59:59') : ''

      params.replaceId = Number(params.replaceId)
      params.empId = userinfo.empId
      if (!params.id) {
        delete params.id
        delete params.versionNum
      }
      delete params.dataTime
      delete params.replaceName
      const { code, data } = await postReplaceHandleApi(params)
      if (code === ERR_OK) {
        ElMessage({
          message: t('keys.saving_succeeded'),
          type: 'success'
        })
        getReplaceHandle()
        resetForm()
        btnLoading.value = false
      } else {
        btnLoading.value = false
      }
    } else {
      btnLoading.value = false
    }
  })
}
getReplaceHandle()

// const descFalg = ref(false)
// const hasMoreArrow = ref(false)

// const hassetMore = () => {
//   hasMoreArrow.value = false
//   nextTick(() => {
//     let scrollHeight = document.getElementsByClassName('infoItemMore')[0].scrollHeight
//     let offsetHeight = document.getElementsByClassName('infoItemMore')[0].offsetHeight
//     hasMoreArrow.value = scrollHeight > offsetHeight
//   })
// }
</script>

<style lang="scss" scoped>
.header {
  padding: 16px 0;
  span {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #333333;
    line-height: 24px;
    &::before {
      content: '';
      width: 2px;
      display: inline-block;
      height: 16px;
      background-color: var(--el-color-primary);
      vertical-align: text-top;
      margin-right: 8px;
    }
  }
}
.demo-ruleForm {
  :deep(.el-form-item__content) {
    justify-content: space-between;
  }
}
.flex-box {
  :deep(.el-form-item) {
    width: calc(100% / 2 - 16px);
    margin-right: 8px;
    margin-bottom: 18px;
  }
}

.desc {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
  word-wrap: break-word;
  position: relative;
  padding: 0 2px;
  line-height: 22px;
  font-size: 14px;
  padding-top: 5px;
  .desc_btn {
    position: absolute;
    right: 0;
    bottom: 0px;
    background: #fff;
    font-size: 12px;
    color: #666666;
    cursor: pointer;
  }
  .transIcon {
    transition: 0.2s all;
    margin-left: 4px;
  }
  .transIcon.transform0 {
    transform: rotate(0deg);
  }
  .transIcon.transform180 {
    transform: rotate(180deg);
  }
}
.descAll {
  padding-bottom: 30px;
  overflow: inherit;
  -webkit-line-clamp: inherit;
}
</style>
